package com.swxc.smartorder.ui.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import com.google.gson.reflect.TypeToken
import com.jaeger.library.StatusBarUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.swxc.smartorder.R
import com.swxc.smartorder.app.CommonAction
import com.swxc.smartorder.app.ConfigSPS
import com.swxc.smartorder.app.GlobalAPI
import com.swxc.smartorder.entity.*
import com.swxc.smartorder.helper.TagAliasOperatorHelper
import com.swxc.smartorder.helper.TagAliasOperatorHelper.ACTION_CLEAN
import com.swxc.smartorder.helper.TagAliasOperatorHelper.sequence
import com.swxc.smartorder.network.NetworkHelper
import com.swxc.smartorder.ui.base.BaseActivity
import com.swxc.smartorder.ui.dialog.LoadingDialog
import com.swxc.smartorder.ui.dialog.SignOutDialog
import com.swxc.smartorder.update.UpdateAppManager
import com.swxc.smartorder.update.utils.OkGoUpdateHttpUtil
import com.swxc.smartorder.utils.*
import com.tbruyelle.rxpermissions2.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.compress.CompressHelper
import com.zhihu.matisse.compress.FileUtil
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy
import com.zhihu.matisse.internal.ui.widget.CropImageView
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_information.*
import java.io.File
import java.util.*


/**
 * 个人信息页面
 */
class InformationActivity : BaseActivity(), View.OnClickListener {

    private var mNetworkHelper: NetworkHelper? = null
    private val signOutDialog = SignOutDialog()

    companion object {

        private const val REQUEST_CODE_CHOOSE = 23
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_editor -> {

                chooseImage()
            }
            R.id.rlayout_about -> {
                readyGo(AboutActivity::class.java)
            }
            R.id.rlayout_feedback -> {
                readyGo(FeedBackActivity::class.java)
            }
            R.id.rlayout_update -> {
                checkUpdate()
            }
            R.id.iv_back -> {
                finish()


            }
            R.id.btn_logout -> {

                val bundle = Bundle()
                bundle.putString("strTitle", "您确定要退出账号吗？")
                bundle.putString("strContent", "退出帐号后，您的信息将不会失去。但您将收不到关于您的任何通知信息。")
                bundle.putString("strSure", "确定退出")
                bundle.putString("strCancel", "取消")
                signOutDialog.arguments = bundle
                signOutDialog.show(supportFragmentManager, "signOut")
                signOutDialog.setOnSureClickListener { logOut() }
            }
        }


    }


    /**
     * 检测更新
     */
    private fun checkUpdate() {


        val updateUrl: String? = GlobalAPI.update

        val versionCode = ApkVersionCodeUtils.getVersionCode(this)
        val params = HashMap<String, String>(2)
        params["appType"] = "WORKORDER_APP"
        params["numberVersion"] = versionCode.toString()
        UpdateAppManager.Builder()

                //当前Activity
                .setActivity(this)
                .setParams(params)
                .setPost(false)
                //更新地址
                .setUpdateUrl(updateUrl)
                //实现httpManager接口的对象
                .setHttpManager(OkGoUpdateHttpUtil())
                .build()
                .update()

    }

    /**
     * 退出登录
     */
    private fun logOut() {


        val httpParams = HttpParams()
        mNetworkHelper?.getRequest(GlobalAPI.signOut, httpParams, object : NetworkHelper.NetWorkHelperBack {
            override fun requestSuccess(json: String) {
                Log.e("退出登录", json)
                val (message, responseCode) = JsonUtil.fromJson(json, BackEntity::class.java)
                        ?: return
                when (responseCode) {
                    1001 -> {
                        AppSharePreferenceMgr.put(mContext, ConfigSPS.TOKEN, "")
                        AppSharePreferenceMgr.put(mContext, ConfigSPS.USER_INFO, "")
                        clearJpushTag()
                        val intent = Intent()
                        intent.setClass(mContext, LoginActivity::class.java)
                        startActivity(intent)
                        signOutDialog.dismiss()
                        CommonAction.getInstance().OutSign()
                    }
                    else -> Toast.makeText(mContext, "退出登录失败,原因：$message", Toast.LENGTH_SHORT).show()
                }

            }

            override fun requestFail() {

            }
        })

    }

    /**
     * 设置极光推送Tag
     */
    private fun clearJpushTag() {
        var tags: Set<String>? = null
        var action = -1
        val tag = AppSharePreferenceMgr.get(mContext, ConfigSPS.PUSH_TAG, "") as String

        if (tag == null || tag.isEmpty()) {
            return
        } else {
            tags = null
        }
        action = ACTION_CLEAN
        val tagAliasBean = TagAliasBean()
        tagAliasBean.action = action
        tagAliasBean.isAliasAction = false
        TagAliasOperatorHelper.getInstance().handleAction(applicationContext, sequence, tagAliasBean)


    }

    /**
     * 选择图片
     */
    private fun chooseImage() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(object : io.reactivex.Observer<Boolean> {
                    override fun onSubscribe(d: Disposable) {}

                    override fun onNext(aBoolean: Boolean) = if (aBoolean) {
                        Matisse.from(this@InformationActivity)
                                .choose(MimeType.of(MimeType.JPEG), false)
                                .countable(false)
                                .capture(true)
                                .captureStrategy(CaptureStrategy(true, "com.swxc.smartorder.fileprovider"))
                                .maxSelectable(1)
                                .isCrop(true)
                                .theme(R.style.matisse)
                                .cropStyle(CropImageView.Style.RECTANGLE)
                                .isCropSaveRectangle(true)
                                .gridExpectedSize(resources.getDimensionPixelSize(R.dimen.grid_expected_size))
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                                .thumbnailScale(0.9f)
                                .imageEngine(GlideEngine())
                                .forResult(REQUEST_CODE_CHOOSE)
                    } else {
                        Toast.makeText(this@InformationActivity, R.string.permission_request_denied, Toast.LENGTH_LONG)
                                .show()
                    }

                    override fun onComplete() {
                    }

                    override fun onError(e: Throwable) {
                    }


                })

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == Activity.RESULT_OK) {
            val file = FileUtil.getFileByPath(Matisse.obtainPathResult(data)[0])
            val file1 = CompressHelper.getDefault(applicationContext).compressToFile(file)
            postAvatar(file1)

        }
    }

    /**
     * 上传头像
     */
    private fun postAvatar(file1: File) {
        val strToken = AppSharePreferenceMgr.get(mContext, ConfigSPS.TOKEN, "") as String
        val loadingDialog = LoadingDialog()
        OkGo.post<String>(GlobalAPI.modifyAvatar)
                .params("access_token", strToken)
                .params("file", file1)
                .isSpliceUrl(true)
                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<*, *>>?) {
                        super.onStart(request)
                        loadingDialog.show(supportFragmentManager, "loadDialog")
                    }

                    override fun onFinish() {
                        super.onFinish()
                        loadingDialog.dismissAllowingStateLoss()
                    }

                    override fun onSuccess(response: Response<String>) {
                        val type = object : TypeToken<CommonData<ModifyAvatar>>() {}.type
                        val fromJson = JsonUtil.fromJson<CommonData<ModifyAvatar>>(response.body(), type)
                                ?: return
                        when (fromJson.responseCode) {
                            1001 -> {
                                val toastUtil = ToastUtil(mContext, true, ToastUtil.STATUS_SUCCESS, "修改头像成功")
                                toastUtil.show(2000)
                                ImageDisplayUtil.showImageView(mContext, fromJson.data.headImage, iv_avatar)
                                AppSharePreferenceMgr.put(mContext, ConfigSPS.AVATAR, fromJson.data.headImage)

                            }
                            else -> {
                                val toastUtil = ToastUtil(mContext, false, ToastUtil.STATUS_ERROR, "修改头像失败")
                                toastUtil.show(2000)
                            }
                        }

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        val toastUtil = ToastUtil(mContext, false, ToastUtil.STATUS_ERROR, "服务器异常")
                        toastUtil.show(2000)
                    }
                })
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_information)
        StatusBarUtil.setColor(this, resources.getColor(R.color.ui_blue_dark), 0)
        initViewAndEvent()
    }

    private fun initViewAndEvent() {
        mNetworkHelper = NetworkHelper(mContext, supportFragmentManager)
        iv_editor.setOnClickListener(this)
        rlayout_about.setOnClickListener(this)
        rlayout_feedback.setOnClickListener(this)
        rlayout_update.setOnClickListener(this)
        iv_back.setOnClickListener(this)
        btn_logout.setOnClickListener(this)

        val userJson = AppSharePreferenceMgr.get(mContext, ConfigSPS.USER_INFO, "") as String
        if (userJson.isEmpty()) {
            return
        } else {
            val userEntity = JsonUtil.fromJson<UserEntity>(userJson, UserEntity::class.java)
            val userAvatar = AppSharePreferenceMgr.get(mContext, ConfigSPS.AVATAR, "") as String
            if (!userAvatar.isEmpty()) {
                ImageDisplayUtil.showImageView(mContext, userAvatar, iv_avatar)
            } else {
                ImageDisplayUtil.showImageView(mContext, userEntity.avatar, iv_avatar)
            }
            tv_name.text = userEntity.name
            tv_phone.text = userEntity.phone
            tv_flag.text = userEntity.organization
        }

    }

}
